<template>
  <div>
    <br />
    <center>
      <div>
        <el-form :inline="true" ref="queryCondition" :model="queryCondition">
          <el-form-item label="相册名称">
            <el-input
              v-model="queryCondition.name"
              placeholder="相册名称"
              @keydown.enter.native="search"
            ></el-input>
          </el-form-item>
          <el-form-item label="所属主题">
            <el-select v-model="queryCondition.themeId" placeholder="所属主题">
              <el-option
                v-for="theme in themeList"
                :key="theme.id"
                :label="theme.title"
                :value="theme.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="是否展示">
            <el-select v-model="queryCondition.status" placeholder="是否展示">
              <el-option label="展示" value="1"></el-option>
              <el-option label="不展示" value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="search()"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh-right" @click="resetForm()"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </center>
    <center>
      <div>
        <el-button
          type="primary"
          @click="opendialog(1)"
          icon="el-icon-circle-plus-outline"
          >添加相册</el-button
        >
        <el-button type="primary" @click="changeShow()">{{showThemeName ? "隐藏主题名字" : "显示主题名字"}}</el-button>
      </div>
    </center>
    <br />
    <center>
      <div>
        <el-table
          :data="albumList"
          stripe
          border
          @selection-change="handleSelectionChange"
        >
          <!-- <el-table-column type="selection" width="80" align="center">
          </el-table-column> -->
          <el-table-column
            prop="name"
            label="相册名称"
            width="280"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="themeTitle"
            label="所属主题"
            width="200"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="coverName"
            label="封面图片"
            width="280"
            align="center"
          >
            <template slot-scope="scope">
              <span
                style="color: rgb(0, 180, 255); cursor: pointer"
                @mouseover="showThumbnail(scope.row.coverUrl)"
                @mouseleave="hideThumbnail"
              >
                {{ scope.row.coverName }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="weight" width="100" align="center">
            <template slot="header">
              <div>
                <span>相册权重</span>
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="权重越大,主题点进去后相册位置越靠前"
                  placement="top"
                >
                  <i class="el-icon-info"></i>
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="photosCount"
            label="照片数量"
            width="100"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="uploadTime"
            label="上传时间"
            width="180"
            align="center"
          >
          </el-table-column>
          <el-table-column label="是否展示" width="100" align="center">
            <template slot-scope="scope">
              {{ scope.row.status == 1 ? "是" : "否" }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="260" align="center">
            <template slot-scope="scope">
              <el-button
                size="mini"
                @click="updateStatus(scope.row.id, scope.row.status)"
                :type="scope.row.status == 1 ? 'info' : 'success'"
              >
                {{ scope.row.status == 1 ? "不展示" : "展示" }}
              </el-button>
              <el-button
                size="mini"
                @click="handleEdit(scope.row.id)"
                type="primary"
                plain
                >编辑</el-button
              >
              <el-button
                size="mini"
                @click="handleAddPhotos(scope.row.id)"
                type="primary"
                >添加照片</el-button
              >
              <!-- <el-button size="mini" type="danger" @click="delById(scope.row.id)">删除</el-button> -->
            </template>
          </el-table-column>
        </el-table>
      </div>
    </center>
    <!-- <div style="width: 500px"><br /></div> -->

    <center>
      <div class="page">
        <el-pagination
          @current-change="handleCurrentChange"
          background
          :current-page.sync="currentPage"
          :page-size="pageSize"
          layout="total, prev, pager, next"
          :total="totalCount"
        >
        </el-pagination>
      </div>
    </center>
    <div>
      <el-dialog
        class="album-dialog"
        :title="title"
        :visible.sync="dialogFormVisible"
        width="30%"
        :top="dialogTop"
        :close-on-click-modal="false"
      >
        <el-form ref="form" :model="album" label-width="80px">
          <el-form-item label="相册名称">
            <el-input
              v-model="album.name"
              placeholder="请输入相册名称"
              style="width: 250px"
              @blur="handleBlur"
            ></el-input>
            <el-form-item>
              <span style="color: red">{{ errorMessage }}</span>
            </el-form-item>
          </el-form-item>
          <el-form-item label="封面图片">
            <!-- 使用 el-upload 组件替换 -->
            <el-upload
              class="avatar-uploader"
              :action="uploadCoverUrl()"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img
                v-if="album.coverUrl"
                :src="album.coverUrl"
                class="avatar"
                style="width: 130px"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              <div
                slot="tip"
                class="el-upload__tip"
                style="margin-top: -20px; margin-bottom: -20px"
                v-if="!this.album.coverUrl"
              >
                请上传一张竖版照片作为相册封面
              </div>
              <div
                slot="tip"
                class="el-upload__tip"
                style="margin-top: -20px; margin-bottom: -20px"
                v-if="!saveFlag"
              >
                点击图片重新上传即可更换封面照片
              </div>
            </el-upload>
          </el-form-item>
          <el-form-item label="所属主题">
            <!-- 使用 el-select 替换 -->
            <el-select v-model="album.themeId" placeholder="请选择所属主题">
              <el-option
                v-for="theme in themeList"
                :key="theme.id"
                :label="theme.title"
                :value="theme.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="相册权重">
            <el-input
              v-model="album.weight"
              placeholder="数字越大,展示的时候越靠前"
              style="width: 250px"
            ></el-input>
          </el-form-item>
          <el-form-item label="上传照片" v-if="saveFlag">
            <!-- 新增拖入式的文件夹上传组件 -->
            <el-upload
              class="upload-photoList"
              drag
              :action="uploadPhotosUrl()"
              multiple
              :before-upload="handleBeforeUpload"
              :on-success="handlePhotosSuccess"
              :show-file-list="false"
              :file-list="fileList"
              v-loading="loading"
              element-loading-text="照片上传中,请稍等"
              element-loading-spinner="el-icon-loading"
              element-loading-background="rgba(0, 0, 0, 0.8)"
              :disabled="uploadDisabled"
              :style="{ 'pointer-events': uploadDisabled ? 'none' : 'auto' }"
            >
              <i class="el-icon-upload" v-if="!loading && !uploadSuccess"></i>
              <div class="el-upload__text" v-if="!loading && !uploadSuccess">
                请拖入单个文件夹或选择多张照片上传 (上限100张)
              </div>
              <!-- 上传成功更换提示和图标 -->
              <i class="success-icon" v-if="uploadSuccess"></i>
              <div class="custom-message" v-if="uploadSuccess">
                {{ uploadSuccessMsg }}
              </div>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false" icon="el-icon-close"
            >取 消</el-button
          >
          <el-button
            type="primary"
            @click="saveOrUpdate()"
            icon="el-icon-check"
            :disabled="disableSubmitButton"
            >提 交</el-button
          >
        </div>
      </el-dialog>
    </div>
    <el-dialog
      class="addPhotos-dialog"
      title="给相册添加照片"
      :visible.sync="dialogPhotosVisible"
      :close-on-click-modal="false"
      width="30%"
      top="200px"
    >
      <el-form ref="form" :model="album" label-width="80px">
        <el-form-item>
          <!-- 新增拖入式的文件夹上传组件 -->
          <el-upload
            class="upload-photoList"
            drag
            :action="uploadPhotosUrl()"
            multiple
            :before-upload="handleBeforeUpload"
            :on-success="handlePhotosSuccess"
            :show-file-list="false"
            :file-list="fileList"
            v-loading="loading"
            element-loading-text="照片上传中,请稍等"
            element-loading-spinner="el-icon-loading"
            element-loading-background="rgba(0, 0, 0, 0.8)"
            :disabled="uploadDisabled"
            :style="{ 'pointer-events': uploadDisabled ? 'none' : 'auto' }"
            style="margin-left: -25px"
          >
            <i class="el-icon-upload" v-if="!loading && !uploadSuccess"></i>
            <div class="el-upload__text" v-if="!loading && !uploadSuccess">
              请拖入单个文件夹或选择多张照片上传 (上限100张)
            </div>
            <!-- 上传成功更换提示和图标 -->
            <i class="success-icon" v-if="uploadSuccess"></i>
            <div class="custom-message" v-if="uploadSuccess">
              {{ uploadSuccessMsg }}
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="margin-top: -30px">
        <el-button @click="dialogPhotosVisible = false" icon="el-icon-close"
          >取 消</el-button
        >
        <el-button
          type="primary"
          @click="addPhotos()"
          icon="el-icon-check"
          :disabled="disableSubmitButton"
          >提 交</el-button
        >
      </div>
    </el-dialog>
    <div
      v-if="hoveredPhotoUrl"
      style="position: absolute; top: 150px; left: 1000px; z-index: 9999"
    >
      <img
        :src="hoveredPhotoUrl"
        style="max-width: 500px; max-height: 500px; width: auto; height: auto"
      />
    </div>
  </div>
</template>

<script>
import { albumApi, themeApi, uploadApi } from "@/api/api";
export default {
  data() {
    return {
      //当前页数
      currentPage: 1,
      //每页显示多少条
      pageSize: 10,
      //总计条数
      totalCount: 0,
      //表的数据
      albumList: [],
      //查询的数据表单
      queryCondition: {
        name: "",
        themeId: "",
        status: "",
      },
      //同名相册错误提示
      errorMessage: "",
      //控制是否显示表单弹框
      dialogFormVisible: false,
      //主题列表
      themeList: [],
      //添加和修改的表单数据
      album: {
        name: "",
        coverName: "",
        coverUrl: "",
        themeId: "",
        weight: "",
        photos: [],
      },
      //选择的id
      ids: [],
      //表单标题
      title: "",
      //提交禁用开关
      disableSubmitButton: false,
      loading: false,
      //上传文件夹成功标识和成功提示
      uploadSuccess: "",
      uploadSuccessMsg: "",
      //保存还是修改,1保存,0修改
      saveFlag: "",
      //弹窗上面距离
      dialogTop: "",
      //上传上册框点击禁用
      uploadDisabled: false,
      // 增加照片弹框开关
      dialogPhotosVisible: false,
      // 缩略图url
      hoveredPhotoUrl: null,
      // 阻止多个文件夹错误提示
      errorMessageShown: false,
      uploadedCount: 0,
      fileList: [], 
      showThemeName: 0,
    };
  },
  methods: {
    //  显示照片缩略图
    showThumbnail(url) {
      this.hoveredPhotoUrl = url;
    },
    // 隐藏照片缩略图
    hideThumbnail() {
      this.hoveredPhotoUrl = null;
    },
    handleAddPhotos(albumId) {
      this.errorMessageShown = false;
      this.uploadSuccess = false;
      this.uploadDisabled = false;
      this.album = {};
      this.dialogPhotosVisible = true;
      this.album.id = albumId;
      this.uploadedCount = 0;
    },
    // 给相册添加照片
    addPhotos() {
      albumApi.addPhotos(this.album).then((resp) => {
        if (resp.data.code) {
          this.$message({
            type: "success",
            message: "照片添加成功",
          });
          this.dialogPhotosVisible = false;
          this.queryPage();
        } else {
          this.$message({
            type: "info",
            message: resp.data.msg,
          });
        }
      });
    },
    //上传封面照片路径
    uploadCoverUrl: function () {
      return process.env.VUE_APP_BACKEND_URL + "/upload/cover";
    },
    // 单张照片上传成功逻辑
    handlePhotosSuccess(res, file, fileList) {
      debugger;
      // 将上传成功的文件数量加1
      this.uploadedCount++;
      if (!Array.isArray(this.album.photos)) {
        this.album.photos = [];
      }
      this.album.photos.push(res.data);
       // 比较已上传的文件数量是否等于总文件数量
      if (this.uploadedCount === fileList.length) {
        // 如果相等，表示所有文件都已经上传成功
        this.loading = false;
        this.disableSubmitButton = false;
        this.uploadSuccess = true;
        this.uploadDisabled = true;
        this.uploadSuccessMsg = "上传成功！共上传了" + fileList.length + "张照片"; // 设置成功提示信息
        // 清空 fileList
        this.fileList = [];
      }
    },
    //上传照片路径
    uploadPhotosUrl: function () {
      return process.env.VUE_APP_BACKEND_URL + "/upload/photos";
    },
    // 修改相册状态
    updateStatus(id, status) {
      //根据现在的状态更换要修改的状态
      const changeStatus = status == 1 ? 0 : 1;
      albumApi.updateStatus(id, changeStatus).then((resp) => {
        if (resp.data.code) {
          this.$message({
            type: "success",
            message: "修改状态成功",
          });
          this.queryPage();
        } else {
          this.$message({
            type: "info",
            message: resp.data.msg,
          });
        }
      });
    },
    //相册弹框验证相册名称
    handleBlur() {
      if (this.album.name == "" || this.album.name == undefined) {
        this.errorMessage = "请输入相册名称";
      } else {
        this.errorMessage = "";
        albumApi.sameAlbumName(this.album).then((resp) => {
          if (resp.data.code) {
            this.errorMessage = "";
          } else {
            this.errorMessage = resp.data.msg;
          }
        });
      }
    },
    //重置查询表单
    resetForm() {
      this.queryCondition.name = "";
      this.queryCondition.themeId = "";
      this.queryCondition.status = "";
      this.queryPage();
    },
    //点击页码切换分页数据
    handleCurrentChange(val) {
      this.currentPage = val;
      this.queryPage();
    },
    //点击搜索按钮
    search() {
      this.currentPage = 1;
      this.queryPage();
    },
    //条件查询
    queryPage() {
      albumApi
        .queryPage(this.currentPage, this.pageSize, this.queryCondition)
        .then((resp) => {
          if (resp.data.code) {
            this.albumList = resp.data.data.records;
            this.totalCount = resp.data.data.total;
            this.showThemeName = resp.data.data.records[0].showThemeName;
          } else {
            this.$message({
              type: "info",
              message: resp.data.msg,
            });
          }
        });
    },
    //查询主题
    queryTheme() {
      themeApi.queryAll("console").then((resp) => {
        if (resp.data.code) {
          this.themeList = resp.data.data;
        } else {
          this.$message({
            type: "info",
            message: resp.data.msg,
          });
        }
      });
    },
    //点击编辑相册信息逻辑
    handleEdit(id) {
      this.opendialog(0);
      albumApi.queryById(id).then((resp) => {
        if (resp.data.code) {
          this.album = resp.data.data;
        } else {
          this.$message({
            type: "info",
            message: resp.data.msg,
          });
        }
      });
    },
    // 上传成功执行逻辑
    handleAvatarSuccess(res, file) {
      this.$set(this.album, "coverUrl", res.data);
    },
    handleBeforeUpload(file) {
      // 如果是文件,直接放行
      if (!file.type == "") {
        this.loading = true;
        this.disableSubmitButton = true;
        return true;
      }
      // 如果拖入多个文件夹直接提示错误
      if (event.dataTransfer.items.length > 1) {
        if (!this.errorMessageShown) {
          this.$message.error("不支持拖入多个文件夹");
          this.errorMessageShown = true;
        }
        return false;
      }
      const promises = [];
      // 获取到这个文件夹
      const item = event.dataTransfer.items[0];
      const entry = item.webkitGetAsEntry();
      // 文件夹的名字
      const folderName = entry.name;
      const reader = entry.createReader();
      // 异步操作 具体咱也不太会
      const promise = new Promise((resolve, reject) => {
        reader.readEntries((entries) => {
          if (entries.length == 0) {
            // 如果文件夹为空，则阻止上传
            this.$message.error("文件夹为空,请检查");
            reject("文件夹为空");
            return false;
          } else if (entries.length > 100) {
            this.$message.error("照片数超过100张");
            reject("照片数超过100张");
            return false;
          }
          // 开启 loading 状态，禁用提交按钮
          this.loading = true;
          this.disableSubmitButton = true;
          // 拿到每个照片文件
          for (const en of entries) {
            if (en.isFile) {
              en.file((file) => {
                // 将读取的文件发送给后端
                this.sendFilesToServer(file, folderName).then(() => {
                  resolve();
                });
              });
            }
          }
        });
      });
      promises.push(promise);

      // 使用 Promise.all 来等待所有异步操作完成
      Promise.all(promises)
        .then(() => {
          // 延迟一段时间后在处理结果,让张片数量填充好
          setTimeout(() => {
            // 关闭 loading 状态，启用提交按钮
            this.loading = false;
            this.disableSubmitButton = false;
            this.uploadSuccess = true;
            this.uploadDisabled = true;
            this.uploadSuccessMsg =
              "上传成功！共上传了" + this.album.photos.length + "张照片";
          }, 1000);
        })
        .catch((error) => {
          console.error(error);
          // 关闭 loading 状态，启用提交按钮
          this.loading = false;
          this.disableSubmitButton = false;
        });
      return false;
    },
    //上传相册中的每张照片
    sendFilesToServer(file, folderName) {
      return new Promise((resolve, reject) => {
        uploadApi
          .uploadPhotos(file, folderName)
          .then((resp) => {
            if (resp.data.code) {
              const photo = resp.data.data;
              if (!Array.isArray(this.album.photos)) {
                this.album.photos = [];
              }
              this.album.photos.push(photo);
              resolve(); // 异步操作成功，调用 resolve
            } else {
              this.$message({
                type: "info",
                message: resp.data.msg,
              });
              reject(resp.data.msg); // 异步操作失败，调用 reject
            }
          })
          .catch((error) => {
            reject(error); // 处理异常情况，调用 reject
          });
      });
    },
    beforeAvatarUpload(file) {
      // 获取文件名
      const fileName = file.name;
      // 找到最后一个点的位置
      const lastIndex = fileName.lastIndexOf(".");
      // 截取文件名部分（不包括后缀）, 赋值给相册名字
      this.album.coverName =
        lastIndex === -1 ? fileName : fileName.substring(0, lastIndex);
      return true;
    },
    saveOrUpdate() {
      if (!this.errorMessage == "") {
        this.$message({
          type: "warning",
          message: "请检查相册名称",
        });
      } else if (
        this.album.coverUrl == "" ||
        this.album.coverUrl == undefined
      ) {
        this.$message({
          type: "warning",
          message: "请上传一张封面照片",
        });
      } else if (this.album.themeId == "" || this.album.themeId == undefined) {
        this.$message({
          type: "warning",
          message: "请选择相册所属主题",
        });
      } else {
        if (this.saveFlag) {
          albumApi.addAlbum(this.album).then((resp) => {
            if (resp.data.code) {
              this.$message({
                type: "success",
                message: "添加相册成功",
              });
              this.dialogFormVisible = false;
              this.queryPage();
            } else {
              this.$message({
                type: "info",
                message: resp.data.msg,
              });
            }
          });
        } else {
          albumApi.updateAlbum(this.album).then((resp) => {
            if (resp.data.code) {
              this.$message({
                type: "success",
                message: "更新相册成功",
              });
              this.dialogFormVisible = false;
              this.queryPage();
            } else {
              this.$message({
                type: "info",
                message: resp.data.msg,
              });
            }
          });
        }
      }
    },
    changeShow(){
      let flag = this.showThemeName == 0 ? 1 : 0;
      albumApi.changeShow(flag).then((resp) => {
            if (resp.data.code) {
              this.showThemeName = flag;
              this.$message({
                type: "success",
                message: "修改成功",
              });
            } else {
              this.$message({
                type: "info",
                message: resp.data.msg,
              });
            }
          });
    },
    //弹出添加或者修改的表单
    opendialog(flag) {
      //flag == 1 添加表单  flag == 0 修改表单
      this.saveFlag = flag;
      if (flag) {
        this.errorMessageShown = false;
        this.uploadSuccess = false;
        this.uploadDisabled = false;
        this.album = {};
        this.errorMessage = "";
        this.title = "添加新相册";
        this.dialogTop = "10px";
      } else {
        this.title = "修改相册";
        this.dialogTop = "110px";
      }
      //打开表单
      this.dialogFormVisible = true;
      this.uploadedCount = 0;
    },
    handleSelectionChange(val) {
      this.ids = [];
      for (let i = 0; i < val.length; i++) {
        this.ids[i] = val[i].id;
      }
    },
  },
  mounted() {
    this.queryPage();
    this.queryTheme();
  },
};
</script>

<style>
.page {
  margin-top: 20px;
}

.el-table td,
.el-table th {
  user-select: none;
}
/* 封面照片弹框调整 */
.custom-dialog .el-dialog__body {
  padding: 5px 5px !important;
  background-color: rgba(255, 255, 255, 0.7);
}
/* 相册新增弹框调整 */
.album-dialog .el-dialog__body {
  padding: 30px 20px 0px 20px !important;
}

.album-dialog .el-dialog__footer {
  padding: 0px 50px 30px 20px !important;
}

.custom-dialog {
  background-color: rgba(255, 255, 255, 0.7);
}

/* 上传封面组件样式 */
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 130px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
/* 相册上传loading */
.upload-photoList .el-loading-text {
  font-size: 18px; /* 调整文字大小 */
  line-height: 60px; /* 设置和上传组件高度相同的行高 */
}

.upload-photoList .custom-message {
  font-size: 18px; /* 调整文字大小 */
  line-height: 160px; /* 设置和上传组件高度相同的行高 */
  color: rgb(175, 175, 14);
}

.upload-photoList .el-loading-spinner {
  /* 调整加载图标大小 */
  font-size: 40px;
  /* 向左上偏移10px */
  margin-top: -40px;
  margin-left: -10px;
}

.upload-photoList {
  height: 180px;
  width: 360px;
}
</style>